﻿using System;

public class FileNameUtils {
	// === Public =====================================================================================================
	public static FileNameUtils CreateInstance() {
		var instance = new FileNameUtils();
		return instance;
	}

	public string GetPathNoEndSeparator(string filename) {
		if (string.IsNullOrEmpty(filename)) {
			return string.Empty;
		}
		var index = IndexOfLastSeparator(filename);
		return index == -1 ? filename : filename.Substring(0, index);
	}

	public string GetNameWithoutExtension(string filename) {
		if (string.IsNullOrEmpty(filename)) {
			return string.Empty;
		}
		var index = IndexOfLastSeparator(filename);
		return index == -1 ? RemoveExtension(filename) : RemoveExtension(filename.Substring(index + 1));
	}

	public string GetExtension(string filename) {
		if (string.IsNullOrEmpty(filename)) {
			return string.Empty;
		}
		var index = IndexOfExtension(filename);
		return index == -1 ? string.Empty : filename.Substring(index + 1);
	}

	public string RemoveExtension(string filename) {
		if (string.IsNullOrEmpty(filename)) {
			return string.Empty;
		}
		var index = IndexOfExtension(filename);
		return index == -1 ? filename : filename.Substring(0, index);
	}

	// === Private ====================================================================================================
	private int IndexOfLastSeparator(string filename) {
		if (string.IsNullOrEmpty(filename)) {
			return -1;
		}
		var lastUnixPos = filename.LastIndexOf(FileConstants.Separators.UNIX);
		var lastWindowsPos = filename.LastIndexOf(FileConstants.Separators.WINDOWS);
		return Math.Max(lastUnixPos, lastWindowsPos);
	}

	private int IndexOfExtension(string filename) {
		if (string.IsNullOrEmpty(filename)) {
			return -1;
		}
		var extensionPos = filename.LastIndexOf(FileConstants.Separators.EXTENSION);
		var lastSeparator = IndexOfLastSeparator(filename);
		return (lastSeparator > extensionPos ? -1 : extensionPos);
	}
}
